package com.geese.module.wechat.service.impl;

import com.geese.common.WXUtil;
import com.geese.common.constants.BusinessConstants;
import com.geese.common.entity.*;
import com.geese.common.util.MD5Util;
import com.geese.common.util.TemplateMsg;
import com.geese.exception.BusinessException;
import com.geese.module.business.dao.BusinessMapper;
import com.geese.module.ceo.dao.CourierMapper;
import com.geese.module.ceo.dao.OrderMapper;
import com.geese.module.user.dao.AccountMapper;
import com.geese.module.user.dao.UserMapper;
import com.geese.module.user.model.SecurityUser;
import com.geese.module.wechat.service.IShopKeeperService;
import com.geese.module.wechat.vo.ShopkeeperOrderVO;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Maps;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * Created by huweiwei on 2017/3/9.
 */
@Service
public class ShopKeeplerServiceImpl implements IShopKeeperService {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private BusinessMapper businessMapper;
    @Autowired
    private CourierMapper courierMapper;
    @Autowired
    private AccountMapper accountMapper;
    @Autowired
    private UserMapper userMapper;

    /**
     * 注册
     * @param password
     */
    @Override
    public void doRegister(Business business, String password) {
        //账号唯一性校验
        String account = business.getMobile();
        Account accountDO = accountMapper.findByAccount(account);
        if (null != accountDO) {
            throw new BusinessException(120076);
        }

        //新增用户信息
        User user = new User();
        user.setUsername(business.getName());
        user.setMobile(account);
        user.setUserType(BusinessConstants.BUSINESS_TYPE);
        user.setBlock(0);
        user.setEnable(1);
        userMapper.save(user);
        Integer userId = user.getId();
        if (null == userId || userId <= 0) {
            throw new BusinessException(120075);
        }

        //获取用户id,新增账号信息
        accountDO = new Account();
        accountDO.setAccount(account);
        accountDO.setEnable(1);
        accountDO.setBlock(0);
        accountDO.setUserId(userId);
        accountDO.setPassword(MD5Util.encrypt(password));
        accountDO.setAllowPoint(0);
        accountMapper.save(accountDO);
        Integer accountId = accountDO.getId();
        if (null == accountId || accountId <= 0) {
            throw new BusinessException(120074);
        }

        //获取用户id,新增商家信息
        // TODO: 2017/3/10 商家工号生成规则
        String code = "";
        business.setCode(code);
        business.setUserId(userId);
        business.setBlock(0);
        business.setAudit(0);
        business.setBlock(0);
        business.setEnable(1);
        businessMapper.insert(business);
        Integer businessId = business.getId();
        if (null == businessId || businessId <= 0) {
            throw new BusinessException(120073);
        }
    }

    /**
     *  派单
     * @return
     */
    @Override
    public Order doPushOrder(Integer userId, String imageUrl) {
        Business business = businessMapper.findByUserId(userId);
        if (null == business) {
            throw new BusinessException(120065);
        }
        if (business.getAudit() != 1) {
            throw new BusinessException(120066);
        }
        if (business.getBlock() == 1) {
            throw new BusinessException(120067);
        }
        Integer code = RandomUtils.nextInt(1000000000, Integer.MAX_VALUE);
        // TODO: 2017/3/9 code生成规则
        Order order = new Order();
        order.setStatus(BusinessConstants.ORDER_STATUS_SEND);
        order.setBusinessId(business.getId());
        order.setCode(code);
        order.setEnable(1);
        order.setImageUrl(imageUrl);
        order.setBusinessName(business.getName());
        order.setSendTime(new Date());
        order.setOrderAmount(business.getOrderAmount());
        orderMapper.insertSelective(order);
        Integer orderId = order.getId();
        if (null == orderId || orderId <= 0) {
            throw new BusinessException(120068);
        }
        
        return order;
    }

    /**
     * 获取商家信息
     * @return
     */
    @Override
    public Map<String, Object> getShopkeeperInfo(Integer userId) {
        Business business = businessMapper.findByUserId(userId);
        if (null == business) {
            throw new BusinessException(120069);
        }
        Map<String, Object> result = new HashMap<>();
        result.put("businessId", business.getId());
        result.put("businessName", business.getName());
        result.put("businessMobile", business.getMobile());
        result.put("businessAddress", business.getAddress());
        return result;
    }

    /**
     * 获取商家订单列表
     * @return
     */
    @Override
    public Map<String, Object> getOrderList(ShopkeeperOrderVO shopkeeperOrderVO, SecurityUser user) {
        Business business = businessMapper.findByUserId(user.getUserId());
        if (null == business) {
            throw new BusinessException(120069);
        }
        shopkeeperOrderVO.setShopkeeperId(business.getId());

        Map<String, Object> result = new HashMap<>();
        PageHelper.startPage(shopkeeperOrderVO.getCurrPage(), shopkeeperOrderVO.getPageSize(), " id DESC");
        List<Order> orderList = orderMapper.selectOrderForShopkeeper(shopkeeperOrderVO);
        Map<String, Object> pageInfo = new HashMap<>();
        if (CollectionUtils.isEmpty(orderList)) {
            pageInfo.put("currPage", 1);
            pageInfo.put("totalPage", 1);
            pageInfo.put("total", 0);
            result.put("pageInfo", pageInfo);
            result.put("orderList", orderList);
            return result;
        }

        List<Map<String, Object>> orders = new ArrayList<>(orderList.size());
        for (Order order : orderList) {
            Map<String, Object> map = new HashMap<>(orderList.size());
            map.put("orderId", order.getId());
            map.put("orderSendTime", order.getSendTime());
            map.put("orderReceiveTime", order.getReceiveTime());
            map.put("orderBusinessName", order.getBusinessName());
            map.put("orderCourierName", order.getCourierName());
            map.put("orderImg", order.getImageUrl());
            map.put("orderCode", order.getCode());
            map.put("orderStatus", order.getStatus());
            orders.add(map);
        }
        PageInfo listInfo = new PageInfo(orderList);
        pageInfo.put("currPage", listInfo.getPageNum());
        pageInfo.put("totalPage", listInfo.getPages());
        pageInfo.put("total", listInfo.getTotal());

        result.put("pageInfo", pageInfo);
        result.put("orderList", orders);
        return result;
    }

    /**
     * 获取订单详情
     * @return
     */
    @Override
    public Map<String, Object> getOrderDetails(int orderId) {
        Order order = orderMapper.selectByPrimaryKey(orderId);
        if (null == order) {
            throw new BusinessException(120070);
        }
        Map<String, Object> result = new HashMap<>();
        result.put("orderCourierMobile", order.getStatus() > 0 ? courierMapper.findById(order.getCourierId()).getMobile() : "");
        result.put("orderId", order.getId());
        result.put("orderSendTime", order.getSendTime());
        result.put("orderReceiveTime", order.getReceiveTime());
        result.put("orderBusinessName", order.getBusinessName());
        result.put("orderCourierName", order.getCourierName());
        result.put("orderImg", order.getImageUrl());
        result.put("orderCode", order.getCode());
        result.put("orderStatus", order.getStatus());
        return result;
    }

    /**
     * 催单
     */
    @Override
    public void doRemind(int orderId) {
        Order order = orderMapper.selectByPrimaryKey(orderId);
        if (null == order) {
            throw new BusinessException(120070);
        }
        if (order.getStatus() != 1) {
            throw new BusinessException(120071);
        }
        Courier courier = courierMapper.findById(order.getCourierId());
        if (courier == null) {
            throw new BusinessException(120072);
        }
        String openId = courier.getOpenId();
        Business business = businessMapper.selectByPrimaryKey(order.getBusinessId());
        Map<String, TemplateMsg.MessageData> data = Maps.newHashMap();
        data.put("first", new TemplateMsg.MessageData(new Date(), "#173177"));
        data.put("remark", new TemplateMsg.MessageData("请尽快送达", "#173177"));
        data.put("keyword1", new TemplateMsg.MessageData(order.getCode(), "#173177"));
        data.put("keyword2", new TemplateMsg.MessageData("已接单", "#173177"));
        data.put("keyword3", new TemplateMsg.MessageData(business.getOrderAmount(), "#173177"));
        if (StringUtils.isNotBlank(openId)) {
            WXUtil.send(openId, data);
        }
    }
}
